-- remote_summon
-- created by wangy
-- 每若干轮自动攻击（召唤兽）

return {
    apply = function(prop, baseValue)
        return prop[3];
    end,

    -- 每回合触发
    trigger = function(who, prop, arg)
        -- 是不是攻击的回合
        local step = tonumber(prop[2]);
        local round = CombatM.getRound();
        local startRound = who.active_round;
        local grid;

        if (round - startRound) % step ~= 0 then
            return false;
        end

        if round <= startRound then
            return false;
        end

        local action = who.action or 0;
        if round <= action then
            return false;
        end

        local target;
        local skillId = prop[3];
        local skills = SkillM.getSkillTable();
        if not skills[skillId] then
            return false;
        end

        local dbase = SkillM.query(skillId, "dbase") or {};
        local skill_target = SkillM.query(skillId, "target");

        -- 目标
        if skill_target == DEFENSER then
            for p = 1, DUNGEON_WIDTH * DUNGEON_HEIGHT do
                grid = DungeonM.getGridByPos(p);

                -- 是未死亡的怪物
                if grid:isOpened() and
                    grid:isMonster() and
                    not grid.monster:isDead() and
                    grid.monster ~= who then
                    target = grid.monster;
                    break;
                end
            end

            -- 已经没有目标了，不处理
            if not target then
                return false;
            end

        else
            if dbase["is_summon"] == 1 then
                target = who;
            elseif dbase["is_user"] == 1 then
                target = ME.user;
            else
                 for p = 1, DUNGEON_WIDTH * DUNGEON_HEIGHT do
                     grid = DungeonM.getGridByPos(p);

                     local summon = grid.summon;

                     -- 不是召唤兽
                     if summon and summon.type == OBJECT_TYPE_SUMMON and
                         not summon:isDead() and summon ~= who then
                         target = summon;
                         break;
                     end
                 end
            end

            -- 已经没有目标了，不处理
            if not target then
                return false;
            end
        end

        -- 记录最经一次行动
        who.action = round;

        local msg = string.format("%s远程魔法，hit_by_user = %s", who:query("name") or "", who.dbase:query("hit_by_user", 0));
        trace("remote_magic", msg);

        -- 初始化序列
        SkillM.initSequence(who, who, 0);

        -- 远程怪攻击动作
        SkillM.getSequence(who):remoteAttack(who, arg, skillId);
        SkillM.apply(who, target, skillId, CombatM.getRound());

        if target == ME.user then
            SkillM.getSequence(arg):start(who, arg, 0);
        end

        return true;
    end,

    record = function(target, prop, path)
        return false;
    end
};
